local base = _G
local math = base.math
module("gui")

ArrowG = {}
ArrowGMT = { __index = ArrowG }

base.setmetatable(ArrowG, { __index = ObjectG })

ArrowG.create = function(x, y, width, height, direction)
  local self = Object(x, y, width, height, ArrowGMT)

  self.styles = get_styles('repeat_delay', 'repeat_rate')
  self.colors = get_colors('border', 'font', 'item', 'background')

  self.direction = direction
  self.is_down = false
  self.time = 0

  return self
end

ArrowG.destroy = function(self)
  self.direction = nil
  self.is_down = nil
  self.time = nil
  
  self.colors = nil
  self.styles = nil
  ObjectG.destroy(self)
end

-- handle mouse input
ArrowG.mouse_press = function(self, button, x, y)
  self.is_down = true
  self.time = 0
  if self:test_point(x, y)== true then
    self:on_click()
  end
end

ArrowG.mouse_release = function(self, button, x, y)
  self.is_down = false
  self.time = 0
end

ArrowG.redraw = function(self, delta)
  local c = self.node.canvas
  c:clear()

  local alpha = 0.5
  if self.is_down == true and self.is_hovered == true then
    alpha = 1
  elseif self.is_hovered == true then
    alpha = 0.75
  end

  -- draw background rectangle
  local l, t, r, b = 0, -self.height, self.width, 0
  c:rect(l, t, r, b)
  c:set_fill_style(self.colors.item, alpha)
  c:fill()

  -- draw the arrow
  local v = 1 - 1/2/2
  local s = math.min(self.width, self.height)
  local xo = math.max(self.width - s, 0)/2
  local yo = math.max(self.height - s, 0)/2 - self.height
  -- todo: make sure the tip of the arrow is exactly 1 pixel
  local x1, y1, x2, y2, x3, y3
  if self.direction == 'up' then
    x1, y1 = xo, s*(1 - v)+ yo
    x2, y2 = s/2 + xo, s*v + yo
    x3, y3 = s + xo, s*(1 - v)+ yo
  elseif self.direction == 'down' then
    x1, y1 = xo, s*v + yo
    x2, y2 = s/2 + xo, s*(1 - v)+ yo
    x3, y3 = s + xo, s*v + yo
  elseif self.direction == 'left' then
    x1, y1 = s*v + xo, yo
    x2, y2 = s*(1 - v)+ xo, s/2 + yo
    x3, y3 = s*v + xo, s + yo
  elseif self.direction == 'right' then
    x1, y1 = s*(1 - v)+ xo, yo
    x2, y2 = s*v + xo, s/2 + yo
    x3, y3 = s*(1 - v)+ xo, s + yo
  end
  c:move_to(x1, y1)
  c:line_to(x2, y2)
  c:line_to(x3, y3)

  c:set_fill_style(self.colors.font, alpha/2)
  c:fill()
end

ArrowG.update = function(self, dt)
  -- register repeated clicks while the button is down
  if self.is_down == true then
    self.time = self.time + dt
    if self.time > self.styles.repeat_delay then
      if self.time > self.styles.repeat_delay + self.styles.repeat_rate then
        self:on_click()
        self.time = self.styles.repeat_delay
      end
    end
  end
  -- todo: don't redraw all the time
  self:redraw(dt)
end

-- events
ArrowG.on_click = function(self)
  
end

Arrow = ArrowG.create